package com.cn.medicalcare.controller.servlet.product;

import com.cn.medicalcare.customtool.IOTool;
import com.cn.medicalcare.customtool.JsonTool;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@WebServlet("/product/insertproduct.json")
@MultipartConfig(maxFileSize = 5*1024*1024)
public class InsertProductServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String category=req.getParameter("category");
        String name=req.getParameter("name");
        String describe=req.getParameter("describe");
        String onshelf=req.getParameter("onshelf");
        String listprice=req.getParameter("listprice");
        String price=req.getParameter("price");
        String description=req.getParameter("description");
        String sendinfo=req.getParameter("sendinfo");
        String cqcinfo=req.getParameter("cqcinfo");
        String payment=req.getParameter("payment");
        String packageinfo=req.getParameter("packageinfo");


        //保存上传的文件
        Part part=req.getPart("img");
        if(part!=null){
            String disposition = part.getHeader("Content-Disposition");
            //获取文件类型
            String suffix = disposition.substring(disposition.lastIndexOf("."),disposition.length()-1);
            //随机的生存一个32的字符串
            String filename = UUID.randomUUID()+suffix;
            String path="D:/hulinbo/projcode/yiliao/front/img/"+category;
            InputStream is = part.getInputStream();
            File file=new File(path);
            file.mkdirs();
            FileOutputStream fos = new FileOutputStream(path+"/"+filename);
            try {
                IOTool.BufferIO(is,fos);
            }catch (IOException e){
                if(file.exists())
                    file.delete();
            }
        }

        Map<String,String> map=new LinkedHashMap<>();
        map.put("status","ok");
        resp.getWriter().print(JsonTool.toJson(map));
    }
}
